<?php
namespace Liaiyong\Light\Service;

use Liaiyong\Light\Core\Service;

abstract class StorageService extends Service {
    protected static $_storageStack = array();
    protected static function getStorage($id = 0) {
        $class = get_called_class();
        if(empty(self::$_storageStack[$class])) {
            self::$_storageStack[$class] = array();
        }
        if (!empty($id)) {
            if(empty(self::$_storageStack[$class][$id])) {
                return array();
            }
            return self::$_storageStack[$class][$id];
        }
        return self::$_storageStack[$class];
    }
    protected static function setStorage($id, $data) {
        $class = get_called_class();
        if(empty(self::$_storageStack[$class])) {
            self::$_storageStack[$class] = array();
        }
        self::$_storageStack[$class][$id] = $data;
    }
    protected static function clearStorage($id = 0) {
        $class = get_called_class();
        if(!empty($id)) {
            if(isset(self::$_storageStack[$class]) && isset(self::$_storageStack[$class][$id])) {
                unset(self::$_storageStack[$class][$id]);
            }
        } else {
            if(isset(self::$_storageStack[$class])) {
                unset(self::$_storageStack[$class]);
            }
        }
        return true;
    }
    public function get($id, $fields = array()) {
        // 读取Storage
        $storage = self::getStorage($id);
        if(!empty($storage)) {
            if(!empty($fields)) {
                return array_diff_key($storage, array_diff_key($storage, array_flip($fields)));
            }
            return $storage;
        }
        // 调用父方法
        $data = parent::get($id, $fields);
        // 存入Storage
        if(!empty($data) && empty($fields)) {
            self::setStorage($id, $data);
        }
        return $data;
    }
    public function upd($id, array $info, $verify = false) {
        $ret = parent::upd($id, $info, $verify);
        if(!empty($ret) && !empty($id)) {
            self::clearStorage($id);
        }
        return $ret;
    }
}
// PHP END
